import unittest
import time
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy

# adb shell dumpsys activity recents | find "intent={" 查看正在运行的包名
capabilities = dict(
    platformName='Android',
    automationName='uiautomator2',
    deviceName='Android',
    appPackage='tv.danmaku.bili',
    appActivity='.MainActivityV2',
    language='en',
    locale='US',
    noReset = True,
    # forceAppLaunch = True # 不配置该项时，可以手动先打开app
)

appium_server_url = 'http://127.0.0.1:4723'

def scroll_down(driver, times, duration):
        for i in range(times):
            driver.swipe(start_x=500, start_y=1200, end_x=500, end_y=700, duration=duration)
            time.sleep(1)

class TestAppium(unittest.TestCase):
    def setUp(self) -> None:
        self.driver = webdriver.Remote(appium_server_url, options=UiAutomator2Options().load_capabilities(capabilities))
        self.driver.implicitly_wait(10)

    def tearDown(self) -> None:
        print('tearDown')
        # if self.driver:
        #     self.driver.quit()

    def test_find_battery(self) -> None:
        # el = self.driver.find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@resource-id="tv.danmaku.bili:id/search_text"]')
        # el.click()

        # el = self.driver.find_element(by=AppiumBy.XPATH, value='//android.widget.EditText[@content-desc="Search query"]')
        # el.send_keys("appium")

        # el = self.driver.find_element(by=AppiumBy.XPATH, value='//android.widget.TextView[@resource-id="tv.danmaku.bili:id/action_search"]')
        # el.click()

        # 首页往下滑动5次
        scroll_down(self.driver, 5, 600)

        # 点击第6个视频
        el = self.driver.find_element(by=AppiumBy.XPATH, value='(//android.widget.ImageView[@resource-id="tv.danmaku.bili:id/cover"])[6]')
        el.click()

        time.sleep(3)

        # 相似列表往下滑动5次
        # scroll_down(self.driver, 5, 600)

        # 点击评论区
        # el = self.driver.find_element(by=AppiumBy.XPATH, value='//android.widget.HorizontalScrollView[@resource-id="tv.danmaku.bili:id/tabs"]/android.widget.LinearLayout/android.widget.LinearLayout[2]')
        # el.click()

        # 评论区往下滑动5次
        # scroll_down(self.driver, 5, 600)

        self.driver.back()

        self.driver.forward()

if __name__ == '__main__':
    unittest.main()